<template>
  <div class="test-page">
    <h1>用户登录状态测试页面</h1>
    
    <div class="test-section">
      <h2>当前登录状态</h2>
      <p><strong>是否已登录:</strong> {{ isLoggedIn ? '是' : '否' }}</p>
      <p><strong>localStorage中的token:</strong> {{ localToken || '无' }}</p>
      <p><strong>localStorage中的userInfo:</strong></p>
      <pre>{{ localUserInfo || '无' }}</pre>
    </div>
    
    <div class="test-section">
      <h2>TheHeader组件状态</h2>
      <p><strong>TheHeader中的用户信息:</strong></p>
      <pre>{{ JSON.stringify(userInfo, null, 2) }}</pre>
    </div>
    
    <div class="test-section">
      <h2>测试操作</h2>
      <button @click="mockRegister" class="test-btn">模拟注册</button>
      <button @click="mockLogin" class="test-btn">模拟登录成功</button>
      <button @click="testLogoutAPI" class="test-btn">测试退出登录API</button>
      <button @click="testLogoutWithCustomHeaders" class="test-btn">测试退出API(自定义请求头)</button>
      <button @click="testUserDropdownLogout" class="test-btn">模拟用户下拉菜单退出</button>
      <button @click="testDirectURL" class="test-btn">直接测试URL连接</button>
      <button @click="simulateLogin" class="test-btn">模拟登录状态</button>
      <button @click="testLogoutButton" class="test-btn">测试退出按钮是否存在</button>
      <button @click="forceLogoutTest" class="test-btn">强制测试退出API（跳过确认）</button>
      <button @click="clearData" class="test-btn">清除数据</button>
      <button @click="refreshPage" class="test-btn">刷新页面</button>
      <button @click="checkStorage" class="test-btn">检查存储</button>
    </div>
    
    <div class="test-section">
      <h2>操作日志</h2>
      <div class="log-container">
        <div v-for="(log, index) in logs" :key="index" class="log-item">
          {{ log }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import logger from '../utils/logger.js'

export default {
  name: 'TestView',
  data() {
    return {
      userInfo: null,
      logs: []
    }
  },
  computed: {
    isLoggedIn() {
      return !!(this.localUserInfo && this.localToken);
    },
    localToken() {
      return localStorage.getItem('token');
    },
    localUserInfo() {
      const userInfoStr = localStorage.getItem('userInfo');
      return userInfoStr ? JSON.parse(userInfoStr) : null;
    }
  },
  methods: {
    addLog(message) {
      const timestamp = new Date().toLocaleTimeString();
      this.logs.unshift(`${timestamp}: ${message}`);
      logger.log(message);
    },
    
    mockRegister() {
      const mockRegisteredInfo = {
        username: 'testuser',
        email: 'test@example.com',
        account: 'test@example.com',
        password: 'testpass123',
        avatar: '',
        id: 123,
        role: 'user',
        registerTime: new Date().toISOString()
      };
      
      localStorage.setItem('registeredUserInfo', JSON.stringify(mockRegisteredInfo));
      this.addLog('模拟注册完成，用户信息已保存到临时存储');
    },
    
    mockLogin() {
      // 模拟完整的登录流程：基于注册信息构造用户数据
      const registeredInfo = localStorage.getItem('registeredUserInfo');
      let userInfo;
      
      if (registeredInfo) {
        try {
          const regInfo = JSON.parse(registeredInfo);
          userInfo = {
            username: regInfo.username || 'test@example.com'.split('@')[0],
            email: 'test@example.com',
            account: 'test@example.com',
            id: regInfo.id || Date.now(),
            avatar: regInfo.avatar || '',
            role: regInfo.role || 'user',
            nickname: regInfo.nickname || regInfo.username || 'Test User',
            phone: regInfo.phone || '',
            realName: regInfo.realName || '',
            loginTime: new Date().toISOString(),
            registerTime: regInfo.registerTime,
            _source: 'frontend_constructed'
          };
          this.addLog('使用注册信息构造用户数据');
        } catch (error) {
          this.addLog('注册信息解析失败，使用默认数据');
        }
      }
      
      // 如果没有注册信息，使用默认数据
      if (!userInfo) {
        userInfo = {
          username: 'testuser',
          email: 'test@example.com',
          account: 'test@example.com',
          id: Date.now(),
          avatar: '',
          role: 'user',
          nickname: 'Test User',
          phone: '',
          realName: '',
          loginTime: new Date().toISOString(),
          _source: 'frontend_constructed'
        };
      }
      
      // 生成token
      const token = 'login_token_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
      
      // 保存到localStorage
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
      localStorage.setItem('token', token);
      localStorage.removeItem('registeredUserInfo'); // 清除注册信息
      
      this.addLog('模拟登录成功，用户: ' + userInfo.username);
      this.checkParentComponent();
    },
    
    // 测试退出登录API
    async testLogoutAPI() {
      try {
        this.addLog('开始测试退出登录API...');
        
        // 检查当前令牌状态
        const token = localStorage.getItem('token');
        if (!token) {
          this.addLog('❌ 没有JWT令牌，无法测试退出登录API');
          return;
        }
        
        this.addLog(`🔑 当前JWT令牌完整内容: ${token}`);
        this.addLog(`🔑 令牌长度: ${token.length}`);
        this.addLog(`🔑 令牌是否以Bearer开头: ${token.startsWith('Bearer ')}`);
        
        // 导入用户API
        const { userApi } = await import('../api/user.js');
        
        // 调用退出登录API
        const response = await userApi.logout();
        this.addLog('✅ 退出登录API调用成功');
        this.addLog(`📥 后端响应: ${JSON.stringify(response)}`);
        
      } catch (error) {
        this.addLog(`❌ 退出登录API调用失败: ${error.message}`);
        this.addLog(`❌ 错误详情: ${JSON.stringify(error.response?.data || error)}`);
      }
    },

    // 测试退出登录API (自定义请求头)
    async testLogoutWithCustomHeaders() {
      try {
        this.addLog('开始测试退出登录API (自定义请求头)...');
        
        const token = localStorage.getItem('token');
        if (!token) {
          this.addLog('❌ 没有JWT令牌');
          return;
        }
        
        this.addLog(`🔑 当前JWT令牌: ${token}`);
        
        // 导入axios配置
        const api = (await import('../api/config.js')).default;
        
        // 直接调用API，测试Authorization头的不同格式
        const testConfigs = [
          { name: 'Authorization(纯令牌)', headers: { 'Authorization': token } },
          { name: 'Authorization(Bearer前缀)', headers: { 'Authorization': `Bearer ${token}` } },
          { name: 'Authorization(Token前缀)', headers: { 'Authorization': `Token ${token}` } },
        ];
        
        for (const config of testConfigs) {
          try {
            this.addLog(`🧪 测试 ${config.name}...`);
            const response = await api.get('/goc/user/logout', { 
              headers: config.headers,
              timeout: 5000 
            });
            this.addLog(`✅ ${config.name} 成功！响应: ${JSON.stringify(response)}`);
            return; // 成功就退出
          } catch (error) {
            this.addLog(`❌ ${config.name} 失败: ${error.response?.status || error.message}`);
          }
        }
        
        this.addLog('❌ 所有请求头字段都失败了');
        
      } catch (error) {
        this.addLog(`❌ 测试失败: ${error.message}`);
      }
    },

    // 测试用户下拉菜单的退出功能
    async testUserDropdownLogout() {
      try {
        this.addLog('===== 模拟用户下拉菜单退出功能 =====');
        
        // 检查登录状态
        const token = localStorage.getItem('token');
        const userInfo = localStorage.getItem('userInfo');
        
        this.addLog(`🔍 当前状态: token=${!!token}, userInfo=${!!userInfo}`);
        if (token) {
          this.addLog(`🔑 JWT令牌: ${token}`);
        }
        
        if (!token) {
          this.addLog('❌ 没有JWT令牌，无法测试退出功能');
          return;
        }
        
        // 模拟用户确认退出（跳过confirm对话框）
        this.addLog('✅ 用户确认退出登录');
        
        this.addLog('🚀 开始调用后端退出登录API...');
        
        // 导入统一API配置
        const { default: API_CONFIG } = await import('../api/apiConfig.js');
        this.addLog(`🌐 目标接口: ${API_CONFIG.getFullURL('/goc/user/logout')}`); // 使用统一配置
        
        // 导入用户API
        const { userApi } = await import('../api/user.js');
        
        // 调用退出登录API
        this.addLog('📞 正在调用 userApi.logout()...');
        const response = await userApi.logout();
        
        this.addLog('✅ 后端退出登录API调用成功！');
        this.addLog(`📥 后端响应: ${JSON.stringify(response)}`);
        
        // 清除本地数据
        localStorage.removeItem('userInfo');
        localStorage.removeItem('token');
        localStorage.removeItem('loginHint');
        
        this.addLog('🧹 本地数据已清除');
        this.addLog('===== 退出流程完成 =====');
        
      } catch (error) {
        this.addLog(`❌ 退出登录失败: ${error.message}`);
        this.addLog(`❌ 错误详情: ${JSON.stringify({
          status: error.response?.status,
          statusText: error.response?.statusText,
          data: error.response?.data
        })}`);
      }
    },

    // 直接测试URL连接
    async testDirectURL() {
      try {
        this.addLog('===== 直接测试URL连接 =====');
        
        const token = localStorage.getItem('token');
        if (!token) {
          this.addLog('❌ 没有JWT令牌，生成测试令牌');
          localStorage.setItem('token', 'test_token_123456');
        }
        
        // 导入统一API配置
        const { default: API_CONFIG } = await import('../api/apiConfig.js');
        this.addLog(`🌐 测试目标URL: ${API_CONFIG.getFullURL('/goc/user/logout')}`);
        
        // 测试多种方式
        const tests = [
          {
            name: '通过axios配置',
            test: async () => {
              const api = (await import('../api/config.js')).default;
              return await api.get('/goc/user/logout', { timeout: 5000 });
            }
          },
          {
            name: '直接fetch请求',
            test: async () => {
              const response = await fetch(API_CONFIG.getFullURL('/goc/user/logout'), {
                method: 'GET',
                headers: {
                  'Authorization': token || 'test_token_123456',
                  'Content-Type': 'application/json'
                }
              });
              return await response.json();
            }
          },
          {
            name: '新axios实例',
            test: async () => {
              const axios = (await import('axios')).default;
              const response = await axios.get(API_CONFIG.getFullURL('/goc/user/logout'), {
                headers: {
                  'Authorization': token || 'test_token_123456',
                  'Content-Type': 'application/json'
                },
                timeout: 5000
              });
              return response.data;
            }
          }
        ];
        
        for (const test of tests) {
          try {
            this.addLog(`🧪 测试: ${test.name}`);
            const result = await test.test();
            this.addLog(`✅ ${test.name} 成功: ${JSON.stringify(result)}`);
          } catch (error) {
            this.addLog(`❌ ${test.name} 失败: ${error.message}`);
            this.addLog(`❌ 错误状态: ${error.response?.status || 'N/A'}`);
            this.addLog(`❌ 错误数据: ${JSON.stringify(error.response?.data || {})}`);
          }
        }
        
        this.addLog('===== URL连接测试完成 =====');
        
      } catch (error) {
        this.addLog(`❌ 测试异常: ${error.message}`);
      }
    },

    // 模拟登录状态
    simulateLogin() {
      try {
        this.addLog('===== 模拟登录状态 =====');
        
        // 创建模拟用户信息
        const mockUserInfo = {
          username: '测试用户',
          email: 'test@example.com',
          account: 'test@example.com',
          avatar: '',
          id: 123,
          role: 'user',
          loginTime: new Date().toISOString()
        };
        
        // 创建模拟JWT令牌
        const mockToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiaWF0IjoxNTE2MjM5MDIyfQ.mock_signature_for_testing';
        
        // 保存到localStorage
        localStorage.setItem('userInfo', JSON.stringify(mockUserInfo));
        localStorage.setItem('token', mockToken);
        
        this.addLog('✅ 模拟登录状态已设置');
        this.addLog(`👤 用户信息: ${JSON.stringify(mockUserInfo)}`);
        this.addLog(`🔑 JWT令牌: ${mockToken}`);
        this.addLog('🔄 请刷新页面或重新加载组件以查看用户下拉菜单');
        
        // 刷新页面使登录状态生效
        setTimeout(() => {
          window.location.reload();
        }, 2000);
        
      } catch (error) {
        this.addLog(`❌ 模拟登录失败: ${error.message}`);
      }
    },

    // 测试退出按钮是否存在
    testLogoutButton() {
      try {
        this.addLog('===== 检查退出按钮是否存在 =====');
        
        // 检查localStorage中的登录状态
        const token = localStorage.getItem('token');
        const userInfo = localStorage.getItem('userInfo');
        
        this.addLog(`🔍 检查登录状态:`);
        this.addLog(`  - token存在: ${!!token}`);
        this.addLog(`  - userInfo存在: ${!!userInfo}`);
        
        if (token) {
          this.addLog(`  - token内容: ${token}`);
        }
        if (userInfo) {
          this.addLog(`  - userInfo内容: ${userInfo}`);
        }
        
        // 检查页面上是否存在用户下拉菜单
        const userDropdown = document.querySelector('.user-dropdown');
        const loginButton = document.querySelector('.login-btn');
        const registerButton = document.querySelector('.register-btn');
        
        this.addLog(`🔍 检查页面元素:`);
        this.addLog(`  - 用户下拉菜单存在: ${!!userDropdown}`);
        this.addLog(`  - 登录按钮存在: ${!!loginButton}`);
        this.addLog(`  - 注册按钮存在: ${!!registerButton}`);
        
        if (userDropdown) {
          this.addLog('✅ 找到用户下拉菜单，可以测试退出功能');
          
          // 尝试找到退出按钮
          const logoutButton = userDropdown.querySelector('.logout');
          this.addLog(`  - 退出按钮存在: ${!!logoutButton}`);
          
          if (logoutButton) {
            this.addLog('✅ 找到退出按钮！');
            this.addLog('💡 请手动点击用户头像展开下拉菜单，然后点击退出按钮');
          }
        } else {
          this.addLog('❌ 未找到用户下拉菜单');
          this.addLog('💡 请先点击"模拟登录状态"按钮创建登录状态');
        }
        
      } catch (error) {
        this.addLog(`❌ 检查失败: ${error.message}`);
      }
    },

    // 强制测试退出API（跳过确认对话框）
    async forceLogoutTest() {
      try {
        this.addLog('===== 强制测试退出API（跳过确认） =====');
        
        // 检查或创建登录状态
        let token = localStorage.getItem('token');
        if (!token) {
          this.addLog('⚠️ 没有JWT令牌，创建测试令牌');
          token = 'test_jwt_token_for_logout_' + Date.now();
          localStorage.setItem('token', token);
          localStorage.setItem('userInfo', JSON.stringify({
            username: '测试用户',
            email: 'test@example.com'
          }));
        }
        
        this.addLog(`🔑 使用JWT令牌: ${token}`);
        this.addLog('🚀 开始直接调用退出API...');
        
        // 直接调用用户API的logout方法
        const { userApi } = await import('../api/user.js');
        
        this.addLog('📞 调用 userApi.logout()...');
        const response = await userApi.logout();
        
        this.addLog('✅ 退出API调用成功！');
        this.addLog(`📥 后端响应: ${JSON.stringify(response)}`);
        this.addLog('🎯 检查Network面板是否有HTTP请求');
        
      } catch (error) {
        this.addLog(`❌ 退出API调用失败: ${error.message}`);
        this.addLog(`❌ 错误状态: ${error.response?.status || 'N/A'}`);
        this.addLog(`❌ 错误数据: ${JSON.stringify(error.response?.data || {})}`);
      }
    },

    clearData() {
      localStorage.removeItem('userInfo');
      localStorage.removeItem('token');
      localStorage.removeItem('registeredUserInfo');
      this.userInfo = null;
      this.addLog('所有数据已清除');
      this.checkParentComponent();
    },
    
    refreshPage() {
      window.location.reload();
    },
    
    checkStorage() {
      this.addLog('检查localStorage...');
      this.addLog(`Token: ${localStorage.getItem('token') || '无'}`);
      this.addLog(`UserInfo: ${localStorage.getItem('userInfo') || '无'}`);
      this.checkParentComponent();
    },
    
    checkParentComponent() {
      // 触发父组件重新检查登录状态
      this.$nextTick(() => {
        // 触发storage事件来通知TheHeader组件
        window.dispatchEvent(new StorageEvent('storage', {
          key: 'userInfo',
          newValue: localStorage.getItem('userInfo')
        }));
        
        this.addLog('已触发TheHeader重新检查登录状态');
      });
    }
  },
  
  mounted() {
    this.addLog('测试页面已加载');
    this.checkStorage();
  }
}
</script>

<style scoped>
.test-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.test-section {
  background: #f5f5f5;
  padding: 20px;
  margin: 20px 0;
  border-radius: 8px;
  border: 1px solid #ddd;
}

.test-section h2 {
  margin-top: 0;
  color: #333;
}

pre {
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ccc;
  overflow: auto;
  font-size: 12px;
}

.test-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  margin: 5px;
  border-radius: 4px;
  cursor: pointer;
}

.test-btn:hover {
  background: #45a049;
}

.log-container {
  max-height: 300px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 10px;
}

.log-item {
  font-family: monospace;
  font-size: 12px;
  margin: 2px 0;
  padding: 2px;
  border-bottom: 1px solid #eee;
}
</style> 